import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.Exception
import java.net.ServerSocket
import java.util.logging.Logger

class SocketServer(cache: Cache) {
    private val logger: Logger = Logger.getLogger(SocketServer::javaClass.name)
    private val port = 9099
    private val commandHandler = CommandHandler(cache)

    init {
        logger.info("initialize socket server on port $port")

        val server = ServerSocket(port)
        val socket = server.accept()

        val clientAddress = socket.inetAddress.hostAddress
        logger.info("client $clientAddress connected")
        val output = PrintWriter(socket.getOutputStream(), true)
        val input = BufferedReader(InputStreamReader(socket.inputStream))
        while (true){
            try {

                val command = input.readLine()
                val result = commandHandler.handle(command)

                output.println("$command -> $result")

            }catch (e: Exception){
                e.printStackTrace()
            }
        }

    }
}